/*
 * @lc app=leetcode.cn id=59 lang=java
 *
 * [59] 螺旋矩阵 II
 *
 * https://leetcode-cn.com/problems/spiral-matrix-ii/description/
 *
 * algorithms
 * Medium (75.12%)
 * Likes:    123
 * Dislikes: 0
 * Total Accepted:    18.1K
 * Total Submissions: 24.1K
 * Testcase Example:  '3'
 *
 * 给定一个正整数 n，生成一个包含 1 到 n^2 所有元素，且元素按顺时针顺序螺旋排列的正方形矩阵。
 *
 * 示例:
 *
 * 输入: 3
 * 输出:
 * [
 * ⁠[ 1, 2, 3 ],
 * ⁠[ 8, 9, 4 ],
 * ⁠[ 7, 6, 5 ]
 * ]
 *
 */

// @lc code=start
class Solution {
    public int[][] generateMatrix(int n) {
        int[][] res = new int[n][n];
        int left = 0, right = n - 1;
        int up = 0, down = n - 1;
        int cnt = 1;
        while (left <= right) {
            //第一行
            for (int i=left; i <= right; i++) {
                res[up][i] = cnt;
                cnt++;
            }
            up++;
            //最后一列
            for (int i=up; i <= down; i++) {
                res[i][right] = cnt;
                cnt++;
            }
            right--;
            //最后一行
            for (int i=right; i >= left; i--) {
                res[down][i] = cnt;
                cnt++;
            }
            down--;
            //第一列
            for (int i=down; i >= up; i--) {
                res[i][left] = cnt;
                cnt++;
            }
            left++;
        }

        return res;
    }
}
// @lc code=end

